<?php

namespace App\Console\Commands\Controller;

use App\Common\Libs\ArrayHelper;
use App\Console\BaseCommand;
use App\Consts\GlobalCounterConst;
use App\Consts\GlobalRelationshipConst;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use App\Models\SysOfficial;
use App\Models\UserFollowingRelationship;

class RelationshipCommand extends BaseCommand
{
    protected $signature = 'controller:relation {action} {json}';

    protected $description = 'relation commands';

    public function count($data)
    {
        $officials = SysOfficial::getInstance()->get();
        if (in_array($data['user_id'], ArrayHelper::getColumn($officials, 'user_id'))) {
            $tableName = UserFollowingRelationship::getBaseTableName() . $data['user_id'];
            $query = UserFollowingRelationship::setTableName($tableName);
        } else {
            $query = UserFollowingRelationship::getModel($data['user_id']);
        }
        $following = $query
            ->where('user_id', $data['user_id'])
            ->whereIn('attention_status', [GlobalRelationshipConst::ATTENTION_STATUS_ATTENTION, GlobalRelationshipConst::ATTENTION_STATUS_EACH])
            ->get();
        $follower = $query
            ->where('user_id', $data['user_id'])
            ->whereIn('attention_status', [GlobalRelationshipConst::ATTENTION_STATUS_FANS, GlobalRelationshipConst::ATTENTION_STATUS_EACH])
            ->get();

        $cacheCount = Cache::getInstance([
            'user_id' => $data['user_id']
        ])->get(CacheKey::COUNTER_USER);
        if (!$cacheCount) {
            $cacheCount = [
                GlobalCounterConst::COUNT_FANS => count($follower),
                GlobalCounterConst::COUNT_ATTENTION => count($following),
            ];
        } else {
            $cacheCount[GlobalCounterConst::COUNT_FANS] = count($follower);
            $cacheCount[GlobalCounterConst::COUNT_ATTENTION] = count($following);
        }

        Cache::getInstance(['user_id' => $data['user_id']])->hset(CacheKey::COUNTER_USER, $cacheCount);
    }

}
